<script setup>
import { ref, watch } from 'vue'
import { ElDialog, ElMessage, ElImageViewer } from 'element-plus'
import axios from '../plugins/axios'

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  dailyList: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:visible'])

// 对话框可见性
const dialogVisible = ref(false)

// 监听 visible 属性变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
})

// 监听对话框可见性变化
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

// Daily 详情数据
const dailyDetail = ref(null)
const loading = ref(false)

// 获取 Daily 详情
const fetchDailyDetail = async () => {
  if (!props.taskId) return
  
  loading.value = true
  try {
    const response = await axios.get(`/daily/getDailyByTaskId/${props.taskId}`)
    if (response.data.code === 1) {
      dailyDetail.value = response.data.data // 这里获取到的是问题反馈列表
    } else {
      ElMessage.error(response.data.msg || '获取详情失败')
    }
  } catch (error) {
    console.error('获取 Daily 详情失败:', error)
    ElMessage.error('获取详情失败')
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  return dateTimeString.replace('T', ' ').split('.')[0]
}

// 获取状态文字
const getStateText = (state) => {
  switch (state) {
    case 1:
      return '未解决'
    case 2:
      return '进行中'
    case 3:
      return '已解决'
    case 4:
      return '已关闭'
    default:
      return '未知状态'
  }
}

// 处理附件下载
const handleDownload = (attachment, attachmentName) => {
  if (!attachment) {
    console.error('附件URL不存在')
    return
  }
  const link = document.createElement('a')
  link.href = attachment
  link.download = attachmentName || '附件'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 图片预览相关
const showImageViewer = ref(false)
const previewImage = ref('')

// 处理媒体点击
const handleMediaClick = (event) => {
  const target = event.target
  
  if (target.tagName === 'IMG') {
    previewImage.value = target.src
    showImageViewer.value = true
  } 
  else if (target.tagName === 'VIDEO') {
    if (document.fullscreenElement) {
      document.exitFullscreen()
    } else {
      target.requestFullscreen()
    }
  }
}

// 关闭图片预览
const closeImageViewer = () => {
  showImageViewer.value = false
}

// 任务详情数据
const taskDetail = ref(null)

// 获取任务详情
const fetchTaskDetail = async () => {
  if (!props.dailyId) return
  
  try {
    const response = await axios.get(`/task/${props.dailyId}`)
    if (response.data.code === 1) {
      taskDetail.value = response.data.data
    } else {
      ElMessage.error(response.data.msg || '获取任务详情失败')
    }
  } catch (error) {
    console.error('获取任务详情失败:', error)
    ElMessage.error('获取任务详情失败')
  }
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return ''
  return timeString.replace('T', ' ').split('.')[0]
}

// 在 dailyDetail 变化时检查并获取任务详情
watch(() => dailyDetail.value, (newVal) => {
  if (newVal && newVal.task !== 0) {
    fetchTaskDetail()
  }
}, { immediate: true })

const handleShare = (id) => {
  const shareUrl = `${window.location.origin}/daily-detail/${id}`
  try {
    navigator.clipboard.writeText(shareUrl)
    ElMessage({
      message: '链接已复制到剪贴板',
      type: 'success',
      duration: 2000
    })
  } catch (err) {
    const input = document.createElement('input')
    input.value = shareUrl
    document.body.appendChild(input)
    input.select()
    document.execCommand('copy')
    document.body.removeChild(input)
    ElMessage({
      message: '链接已复制到剪贴板',
      type: 'success',
      duration: 2000
    })
  }
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="问题反馈详情"
    width="70%"
    :before-close="handleClose"
    v-loading="loading"
    class="daily-detail-dialog"
  >
    <div v-if="props.dailyList.length > 0" class="daily-list">
      <div v-for="daily in props.dailyList" :key="daily.id" class="daily-detail">
        <!-- 标题部分 -->
        <div class="daily-title">
          <div class="title-left">
            <h3>{{ daily.title }}</h3>
            <span class="state-tag" :class="`state-${daily.state}`">
              {{ getStateText(daily.state) }}
            </span>
          </div>
          <button class="action-btn share" @click="handleShare(daily.id)">
            <i class="el-icon-share"></i>
            分享
          </button>
        </div>
        
        <!-- 基本信息 -->
        <div class="daily-info">
          <div class="info-row">
            <span>记录人：{{ daily.user?.realname }}</span>
            <span>发生时间：{{ formatDateTime(daily.happendTime) }}</span>
          </div>
          <div class="info-row">
            <span>机器编号：{{ daily.equipment?.equipmentName }}</span>
            <span>部件：{{ daily.component?.componentName }}</span>
          </div>
        </div>

        <!-- 问题描述 -->
        <div class="daily-description">
          <h4 class="description-title">问题描述</h4>
          <div v-html="daily.description" @click="handleMediaClick"></div>
        </div>

        <div class="attachments" v-if="daily.attachments?.length">
          <span
            v-for="file in daily.attachments"
            :key="file.id || file.fileUrl"
            class="attachment"
            @click="handleDownload(file.fileUrl, file.fileName)"
          >
            📎 {{ file.fileName || '附件' }}
          </span>
        </div>

        <div class="divider"></div>
      </div>
    </div>
    <div v-else class="no-data">暂无相关问题反馈数据</div>

    <!-- 添加图片预览组件 -->
    <el-image-viewer
      v-if="showImageViewer"
      @close="closeImageViewer"
      :url-list="[previewImage]"
    />
  </el-dialog>
</template>

<style scoped>
.daily-detail-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.daily-list {
  width: 100%;
}

.daily-detail {
  width: 100%;
  padding: 24px 30px;
  box-sizing: border-box;
}

.daily-title {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.daily-title h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.daily-info {
  width: 100%;
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 16px 20px;
  margin-bottom: 20px;
  box-sizing: border-box;
}

.info-row {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  margin-bottom: 12px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-row span {
  width: 50%;
  color: #606266;
  font-size: 14px;
}

.daily-description {
  width: 100%;
  margin-top: 24px;
}

.description-title {
  width: 100%;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px 0;
}

.daily-description div {
  width: 100%;
  color: #606266;
  line-height: 1.6;
  font-size: 14px;
}

.state-tag {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 13px;
}

.state-1 {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fbc4c4;
}

.state-2 {
  background-color: #fdf6ec;
  color: #e6a23c;
  border: 1px solid #f5dab1;
}

.state-3 {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #c2e7b0;
}

.state-4 {
  background-color: #f4f4f5;
  color: #909399;
  border: 1px solid #d3d4d6;
}

.divider {
  width: 100%;
  height: 1px;
  background-color: #EBEEF5;
  margin: 24px 0;
}

.no-data {
  width: 100%;
  text-align: center;
  padding: 40px 0;
  color: #909399;
  font-size: 14px;
}

.action-btn {
  margin-right: 8px;
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.action-btn.share {
  background-color: #67C23A;
  color: white;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.action-btn:hover {
  opacity: 0.8;
}

.action-btn i {
  font-size: 12px;
}
.attachments {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 12px;
}

.attachment {
  cursor: pointer;
  color: #409eff;
  font-size: 14px;
}

</style> 
